package com.jvxb.manage.livable.controller;

import com.baomidou.mybatisplus.core.conditions.Condition;
import com.jvxb.common.utils.EncrypDESUtil;
import com.jvxb.common.web.RespMsg;
import com.jvxb.manage.livable.entity.SysUser;
import com.jvxb.manage.livable.service.SysUserService;
import com.jvxb.modules.configuration.security.SecurityConstant;
import com.jvxb.modules.configuration.security.TokenProvider;
import com.jvxb.modules.configuration.security.UserDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Api(tags = "登录相关接口")
@Log4j2
public class LoginController {

    @Autowired
    private SysUserService userService;
    @Autowired
    private TokenProvider tokenProvider;

    @ApiOperation(value = "用户登录")
    @PostMapping(value = "/login")
    @ApiImplicitParams({@ApiImplicitParam(name = "name", value = "用户名", dataType = "String", required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", required = true)})
    public RespMsg<String> login(@RequestBody SysUser userVo) throws Exception {
        SysUser user = userService.getOne(Condition.<SysUser>create().eq(SysUser.LOGIN_NAME, userVo.getUserName()));
        if (user == null) {
            return RespMsg.error(SecurityConstant.ERROR_ACCOUNT_OR_PASSWORD, "账号或者密码不正确！");
        }
        if (!new EncrypDESUtil().encrypt(userVo.getPassword()).equals(user.getPassword())) {
//            throw new ServiceException(SecurityConstant.ERROR_ACCOUNT_OR_PASSWORD, "账号或者密码不正确！");
            log.error("账号或者密码不正确！");
        }
        UserDetail userDetail = new UserDetail();
        beanCopy(user, userDetail);
        String token = tokenProvider.createToken(userDetail);
        return RespMsg.ok(token);
    }

    private void beanCopy(SysUser user, UserDetail userDetail) {
        userDetail.setId(user.getId());
        userDetail.setLoginName(user.getLoginName());
        userDetail.setPhone(user.getPhone());
        userDetail.setUserName(user.getUserName());
        userDetail.setUserCode(user.getUserCode());
        userDetail.setRoles(user.getRoleId().toString());
        userDetail.setDepartmentName(user.getDepartmentName());
    }

    @RequestMapping("/sessionTimeout")
    public RespMsg<String> timeout() {
        return RespMsg.error(4000, "session过期或无效。");
    }
}
